import { Request, Response, NextFunction } from 'express'

export const sort = (req: Request, res: Response, next: NextFunction) => {
  const { sort } = req.query

  let sqlSort: string

  switch (sort) {
    case 'earliest':
      sqlSort = 'post.id ASC'
      break
    case 'latest':
      sqlSort = 'post.id DESC'
      break
    case 'most_comments':
      sqlSort = 'total_comments DESC, post.id DESC'
      break
    default:
      sqlSort = 'post.id DESC'
  }

  req.sort = sqlSort
  next()
}

export const filter = (req: Request, res: Response, next: NextFunction) => {
  const { tag, user, action } = req.query

  req.filterParmas = {
    name: 'default',
    sql: 'post.id  IS NOT NULL'
  }

  if (tag && !(user || action)) {
    req.filterParmas = {
      name: 'tagName',
      sql: 'tag.name = ?',
      param: tag as string
    }
  }
  if (user && action == 'published' && !tag) {
    req.filterParmas = {
      name: 'userPublished',
      sql: 'user.id = ?',
      param: user as string
    }
  }

  if (user && action == 'liked' && !tag) {
    req.filterParmas = {
      name: 'userLiked',
      sql: 'user_like_post.user_id = ?',
      param: user as string
    }
  }

  next()
}

export const pagination = (req: Request, res: Response, next: NextFunction) => {
  const { page = 1, size = 10 } = req.query

  const limit = +size
  const offset = (+page - 1) * limit

  req.pagination = { limit, offset }

  next()
}
